package com.jnu.myllm.mapper;

import org.apache.ibatis.annotations.*;
import com.jnu.myllm.entity.Record;
import java.util.Date;
import java.util.List;

@Mapper
public interface RecordMapper {
    // 插入记录
    @Insert("insert into records values(default, #{r.userId}, #{r.tokens}, now(), #{r.pay}, #{r.question}, #{r.answer})")
    int insertrecord(@Param("r")Record record);

    // 记录表外连接用户表
    @Select("select rec_id as id, rec_user_id as userId, rec_token as tokens, " +
            "rec_time as oprTime, rec_pay as pay, u.user_nickname as nickName, " +
            "rec_question as question, rec_answer as answer " +
            "from records r join users u on r.rec_user_id = u.user_id " +
            "where rec_user_id = #{uid} " +
            "order by id desc")
    List<Record> selectByUser(@Param("uid") int userId);

    // 函数的参数名必须和注解的参数名一致，如果只有一个参数，sql语句的参数名可以省略或用其他名字
    // 简单的条件放前面可以加速
    @Select("select count(*) from records where records.rec_user_id = #{userId} and to_days(rec_time)=to_days(#{date})")
    int selectCountByDate(@Param("date") Date date, @Param("userId") int userId);

    // 删除除了最新四条的记录
    @Delete("delete\n" +
            "from records\n" +
            "where rec_user_id = #{uid}\n" +
            "  and rec_id not in\n" +
            "      (select rec_id from records where rec_user_id=#{uid} order by rec_time desc limit 4);")
    int deleteByUser(@Param("uid")int userId);
}
